/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.model.saver.bufferedwriter;

import java.io.BufferedWriter;
import java.io.IOException;

import com.nebrija.riif.model.ChildComponentList;
import com.nebrija.riif.model.ChildComponentUnit;
import com.nebrija.riif.model.Component;
import com.nebrija.riif.model.RIIFElement;
import com.nebrija.riif.model.RIIFProperties;
import com.nebrija.riif.model.saver.ChildComponentListSaver;
import com.nebrija.riif.model.saver.ChildComponentUnitSaver;
import com.nebrija.riif.model.saver.ComponentSaver;
import com.nebrija.riif.model.saver.RIIFPropertiesSaver;
import com.nebrija.riif.model.saver.RIIFSaverFactory;

/**
 * Implementation of an ComponentWriterFormatSaver that writes the object to a BufferedWriter
 * @author asanchep
 *
 */
public class ComponentWriterFormatSaver implements ComponentSaver{

	public static final String COMPONENT_TOKEN = "component";
	public static final String END_COMPONENT_TOKEN = "endcomponent";

	/** Writer where the information about the object is sent */
	private BufferedWriter out;
	/** Factory used to create other elements of the saver family */
	private RIIFSaverFactory factory;
	
	/**
	 * Creates an ChildComponentListWriterFormatSaver
	 * @param bw Writer where the information about the object is sent
	 * @param factory Factory used to create other elements of the saver family
	 */
	public ComponentWriterFormatSaver (BufferedWriter bw, RIIFSaverFactory factory){
		out=bw;
		this.factory=factory;
	}
	
	@Override
	public void save(Component component) {
		if(out==null){
			return;
		}
		try{
			// print the component information following the grammar syntax
			out.append(COMPONENT_TOKEN).append(" ").append(component.getName()).append(";\n\n");
			// Use savers for every Child Component or RIIFProperties object contained in the component
			RIIFPropertiesSaver saver = factory.getRIIFPropertiesSaver();
			ChildComponentUnitSaver ccuSaver = factory.getChildComponentUnitSaver();
			ChildComponentListSaver cclSaver = factory.getChildComponentListSaver();
			for(RIIFElement element:component.getElements().values()){
				if (element instanceof RIIFProperties){
					saver.save((RIIFProperties)element);
				}else if (element instanceof ChildComponentUnit){
					ccuSaver.save((ChildComponentUnit)element);
				}else if (element instanceof ChildComponentList){
					cclSaver.save((ChildComponentList)element);
				}
			}
			// print endcomponent label
			out.append(END_COMPONENT_TOKEN).append("\n");
			out.flush();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
		
	}

}
